﻿using System;
using System.Collections.Generic;
using System.Threading;
using CookComputing.XmlRpc;

namespace CRMWeb.Utilities
{
    public class EmailHelper
    {
        public string EmailName { get; set; }
        public string FromName { get; set; }
        public string FromAddress { get; set; }
        public List<string> ToAddressList { get; set; }
        public string Subject { get; set; }
        public string HtmlContent { get; set; }

        public string Send()
        {
            var wrapper = new XmlRpcWrapper();

            // Login
            wrapper.login("cashfinance", "nunimes31"); //Web.config

            // Database (List)
            var databases = (XmlRpcStruct)wrapper.getDatabaseByName("Test List"); //Web.config
            var database = (XmlRpcStruct)databases["0"];
            database = (XmlRpcStruct)database["0"];

            // Contact
            var contacts = new XmlRpcStruct();
            for (var i = 0; i <= ToAddressList.Count - 1; i++)
            {
                var contact = new XmlRpcStruct();
                contact["Email"] = ToAddressList[i];
                contacts.Add((i+1).ToString(), contact);
            }
            contacts = (XmlRpcStruct)wrapper.addContacts(Convert.ToInt32(database["id"]), contacts);               

            // Email
            var email = new XmlRpcStruct();
            email["email_name"] = EmailName;
            email["type"] = "html";
            email["subject"] = Subject;
            email["from_name"] = FromName;
            email["from_address"] = FromAddress;
            email["folder_id"] = 246006; //Web.config
            email["html_content"] = HtmlContent;
            email["id"] = wrapper.addEmail(email);

            // Campaign
            var campaign = new XmlRpcStruct();
            campaign["db_id"] = Convert.ToInt32(database["id"]);
            campaign["type"] = "contacts";
            campaign["list"] = contacts;
            campaign["time"] = "now";
            var campaigns = new XmlRpcStruct();
            campaigns.Add("1", campaign);
            //Campaign Queue
            var queue_id = wrapper.addCampaign(Convert.ToInt32(email["id"]), campaigns);
            //Campaign Population
            Thread.Sleep(3000);
            var campaignId = wrapper.getCampaignIdByQueueId(Convert.ToInt32(queue_id));

            return campaignId.ToString();
        }

    }
}